package com.ruoyi.common.deep;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;


public class OllamaClient {

    public static void main(String[] args) {
        sendRequestStream("我是花菜菜, 你是谁?");
    }

    public static void sendRequestStream(String prompt) {
        try {
            // Ollama服务的URL
            String ollamaUrl = "http://127.0.0.1:11434/api/generate";

            String deepSeekEdition = "deepseek-r1:1.5b";

            // 创建URL对象
            URL url = new URL(ollamaUrl);

            // 打开连接
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/json; utf-8");
            conn.setRequestProperty("Accept", "application/json");
            conn.setDoOutput(true);

            // 请求体
            String jsonInputString = "{\"model\": \"" + deepSeekEdition + "\", \"prompt\": \"" + prompt + "\"}";

            // 发送请求
            try (OutputStream os = conn.getOutputStream()) {
                byte[] input = jsonInputString.getBytes(StandardCharsets.UTF_8);
                os.write(input, 0, input.length);
            }

            // 获取响应
            int responseCode = conn.getResponseCode();
            System.out.println("Response Code: " + responseCode);

            // 流式读取并处理响应内容
            try (BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"))) {
                String responseLine;
                while ((responseLine = br.readLine()) != null) {
                    JsonObject jsonResponse = JsonParser.parseString(responseLine).getAsJsonObject();
                    String responseContent = jsonResponse.get("response").getAsString();
                    System.out.print(responseContent); // 实现流式输出
                    boolean done = jsonResponse.get("done").getAsBoolean();
                    if (done) break;
                }
            }

            // 关闭连接
            conn.disconnect();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
